/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.view.css;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import offset.nodes.server.view.UserAgentDetector;

/**
 *
 * @author Walter L�tgenau
 */
public class CssInputStream extends InputStream {
    InputStream input;

    /**
     * Create a css input stream from the css input stream.
     *
     * The new stream will have the preprocessor commands of the input already preprocessed.
     *
     * @param request the request
     * @param css the css input stream
     * @throws IOException an io exception
     */
    public CssInputStream(HttpServletRequest request, InputStream css) throws IOException {
        byte[] buf = new byte[css.available()];
        css.read(buf);
        this.input = new ByteArrayInputStream(CssPreProcessor.getInstance().preProcess(getUserSettings(request), new String(buf)).getBytes());
    }

    @Override
    public int read() throws IOException {
        return input.read();
    }

    /**
     * Return a map of user settings from the request
     *
     * @param request the request
     * @return the user settings
     */
    protected HashMap<String,String> getUserSettings(HttpServletRequest request) {
        UserAgentDetector ua = UserAgentDetector.getInstance(request);

        HashMap<String,String> result = new HashMap<String,String>();
        result.put("ua", ua.getUserAgent());
        result.put("uaType", ua.getUserAgentType());
        result.put("uaVersion", ua.getUserAgentVersion());
        result.put("os", ua.getOperatingSystem());
        result.put("osType", ua.getOperatingSystemType());
        result.put("osVersion", ua.getOperatingSystemVersion());
        result.put("country", request.getLocale().getCountry());
        result.put("language", request.getLocale().getLanguage());

        return result;
    }
}
